<template>
    <div class="quality-check-resultAll">
      <affix :quality="isShow" :label="$t('intelligentQualityCheck.intelQueryCondition')" @isFold="isFold">
        <div v-show="isShowCon">
          <div class="templa">
            <span class="temp">{{$t('intelligentQualityCheck.intelQualityType')}}：</span>
            <el-radio-group v-model="webOrCallOrTaskTemp" @change="tempStateChange">
              <el-radio :label="1">{{$t('intelligentQualityCheck.intelCallQuality')}}</el-radio>
              <el-radio :label="2">{{$t('intelligentQualityCheck.intelWebChatQuality')}}</el-radio>
              <el-radio :label="3">{{$t('intelligentQualityCheck.intelTaskQuality')}}</el-radio>
            </el-radio-group>
          </div>
          <!--通话质检-->
          <div v-show="callIsShow">
            <el-form labelPosition="top" :inline="true" :model="callForm" ref="callForm"  class="call-form-inline form-inline">
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item :label="$t('public.callTime')+':'">
                    <el-date-picker size="mini"
                                    :id="['z1','z2']"
                                    v-model="callForm.callTime"
                                    :editable="boolean"
                                    type="datetimerange"
                                    :picker-options="pickerOptions"
                                    :placeholder="$t('public.timeRanges')"
                                    align="right"
                                    @change="callTimeChange">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('call.callType')+':'">
                    <el-select size="mini" v-model="callForm.callType" multiple filterable :placeholder="$t('webchat.webchatAll')">
                      <el-option
                        v-for="(item, index) in callTypeList"
                        :key="index"
                        :label="item.code_name"
                        :value="item.code_value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('call.callRingSeat')+':'">
                    <el-popover
                      ref="popover4"
                      placement="bottom"
                      @show="popoverShow"
                      width="240"
                      trigger="click">
                      <agent-tree :readSeat="folllowedAgents" ref="agentTree" @saveFollowedAgents="saveFollowedAgents"></agent-tree>
                    </el-popover>
                    <div class="follow-agent-wrap" v-popover:popover4>
                        <span class="follow-agent follow-common" v-for="item in folllowedAgents" :key="item._id">{{item.label}}
                          <i class="el-icon-close" @click.stop="closeFollowedAgents(item._id)"></i>
                        </span>
                      <div>
                        <span type="primary" class="follow-agent-wrap-btn"><i class="el-icon-arrow-down" style="color: #c0c4cc"></i></span>
                      </div>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('public.queues')+':'">
                    <el-select size="mini" v-model.trim="callForm.toPeer" multiple filterable :placeholder="$t('qualityCheck.skillGroupSearch')">
                      <el-option
                        v-for="(item, index) in queueList"
                        :key="index"
                        :label="item.DisplayName"
                        :value="item.DisplayName">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item :label="$t('qualityCheck.callingNumber')+':'" prop="fromCid">
                    <el-input size="mini" v-model.trim="callForm.fromCid" :placeholder="$t('qualityCheck.pleaseEnterCallingNum')"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('qualityCheck.calledNumber')+':'" prop="fromDid">
                    <el-input size="mini" :placeholder="$t('qualityCheck.pleaseEnterCalledNum')" v-model.trim="callForm.fromDid"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('public.satisfaction')+':'">
                    <!--<el-select size="mini" v-model.trim="callForm.satisfaction" filterable :placeholder="$t('public.satisfaction')">-->
                      <!--<el-option :label="'&#45;&#45;'+$t('webchat.webchatAll')+'&#45;&#45;'" value=""></el-option>-->
                      <!--<el-option-->
                        <!--v-for="(item, index) in satisfactionList"-->
                        <!--:key="index"-->
                        <!--:label="item.name"-->
                        <!--:value="item.value">-->
                      <!--</el-option>-->
                    <!--</el-select>-->
                    <!--二级满意度-->
                    <!--{{investigateArray}}-->
                    <el-cascader
                      style="width:100%;"
                      :options="investigateArray"
                      v-model.trim="INVESTIGATE"
                      change-on-select
                      @change="changeData(INVESTIGATE)"
                    ></el-cascader>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('intelligentQualityCheck.intelCallLength')+':'">
                    <el-input size="mini" style="width: calc(50% - 30px)" v-model.trim="callForm.callTimeLengthStart">
                    </el-input>
                    <span class="line"></span>
                    <el-input size="mini" style="width: calc(50% - 30px)" v-model.trim="callForm.callTimeLengthEnd">
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item :label="$t('qualityCheck.qualityControlPersonnel')+':'">
                    <el-select size="mini" v-model="callForm.gradeUser" multiple filterable :placeholder="$t('public.pickAgentTip1')">
                      <el-option
                        v-for="(item, index) in callAgentList"
                        :key="index"
                        :label="item.displayName + '[' + item.exten + ']'"
                        :value="item._id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('intelligentQualityCheck.intelQualityRule')+':'">
                    <el-select size="mini" multiple v-model="callForm.ruleId" collapse-tags>
                      <el-option
                        v-for="(item, index) in qualityRuleList"
                        :disabled="item._id!==''&&callForm.ruleId.indexOf('')!==-1"
                        :key="index"
                        :label="item.name"
                        :value="item._id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('intelligentQualityCheck.intelTaskQuality')+':'">
                    <el-select size="mini" v-model="callForm.taskId" multiple collapse-tags>
                      <el-option
                        v-for="(item, index) in qualityCallTaskList"
                        :disabled="item._id!==''&&callForm.taskId.indexOf('')!==-1"
                        :key="index"
                        :label="item.name"
                        :value="item._id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('intelligentQualityCheck.intelGradeNum')+':'">
                    <el-input size="mini"  v-model.trim="callForm.gradeAmountStart" style="width: calc(50% - 30px)">
                    </el-input>
                    <span class="line"></span>
                    <el-input size="mini" v-model.trim="callForm.gradeAmountEnd" style="width: calc(50% - 30px)">
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                  <el-col :span="6">
                    <el-form-item :label="$t('call.callNumber')+':'">
                      <el-input size="mini" v-model.trim="callForm._id" :placeholder="$t('public.pleaseEnter')"></el-input>
                    </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <!--在线咨询质检-->
          <div v-show="webChatIsShow">
            <el-form labelPosition="top" :inline="true" :model="webChatform" ref="webChatform"  class="webChat-form-inline form-inline">
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item :label="$t('intelligentQualityCheck.intelChannelAgents')+':'">
                    <el-popover
                      ref="popover5"
                      placement="bottom"
                      @show="popoverShow"
                      width="240"
                      trigger="click">
                      <agent-tree :readSeat="webFolllowedAgents" ref="agentTree" @saveFollowedAgents="saveWebFollowedAgents"></agent-tree>
                    </el-popover>
                    <div class="follow-agent-wrap" style="width: calc(100% - 16px)" v-popover:popover5>
                        <span class="follow-agent follow-common" v-for="item in webFolllowedAgents" :key="item._id">{{item.label}}
                          <i class="el-icon-close" @click.stop="closeWebFollowedAgents(item._id)"></i>
                        </span>
                      <div>
                        <span type="primary" class="follow-agent-wrap-btn"><i class="el-icon-arrow-down" style="color: #c0c4cc"></i></span>
                      </div>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('intelligentQualityCheck.intelEndType')+':'">
                    <!-- <el-select size="mini" v-model.trim="webChatform.finishKey" filterable :placeholder="$t('webchat.webchatAll')"> -->
                      <!-- <el-option value="" :label="'--'+$t('webchat.webchatAll')+'--'"></el-option>
                      <el-option
                        v-for="(item, index) in finishReasonList"
                        :key="index"
                        :label="item.name"
                        :value="item.key"
                      >
                      </el-option> -->
                    <!-- </el-select> -->
                    <el-cascader
                      popper-class="webchat-finish"
                      style="width: 100%"
                      :options="closeOptions"
                      filterable
                      v-model.trim="activeFinish"
                      change-on-select
                    ></el-cascader>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('public.satisfaction')+':'">
                    <el-select size="mini" v-model.trim="webChatform.appraiseKey" filterable :placeholder="$t('webchat.webchatAll')">
                      <el-option value="" :label="'--'+$t('webchat.webchatAll')+'--'"></el-option>
                      <el-option :label="'--'+$t('public.unevaluated')+'--'" value="unevaluated"></el-option>
                      <el-option
                        v-for="(item, index) in appraiseList"
                        :key="index"
                        :label="item.name"
                        :value="item.key"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('webchat.platformSource')+':'">
                    <el-select size="mini" v-model.trim="webChatform.platform" :placeholder="$t('public.all')">
                      <el-option :label="'--'+$t('webchat.webchatAll')+'--'" value=""></el-option>
                      <el-option
                        v-for="(item, index) in platforms"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item :label="$t('intelligentQualityCheck.intelReceiveTime')+':'">
                    <el-date-picker size="mini"
                                    :id="['k1','k2']"
                                    v-model.trim="webChatform.checkTime"
                                    :editable="boolean"
                                    type="datetimerange"
                                    :picker-options="pickerOptions"
                                    :placeholder="$t('public.timeRanges')"
                                    align="right"
                                    @change="getTimeChange">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('webchat.msgNum')+':'">
                    <el-radio-group style="width:calc(100% - 62px);" v-model.trim="webChatform.msgCountType">
                      <el-radio size="mini" label="gt" >{{$t('webchat.moreThan')}}</el-radio>
                      <el-radio size="mini" label="lt" >{{$t('webchat.lessThan')}}</el-radio>
                      <el-radio size="mini" label="eq" >{{$t('webchat.equal')}}</el-radio>
                    </el-radio-group>
                    <el-input style="width:60px;" size="mini" v-model.trim="webChatform.msgCount" :placeholder="$t('public.pleaseInput')"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('qualityCheck.qualityControlPersonnel')+':'">
                    <el-select size="mini" v-model="webChatform.gradeUser" multiple filterable :placeholder="$t('public.pickAgentTip1')">
                      <el-option
                        v-for="(item, index) in callAgentList"
                        :key="index"
                        :label="item.displayName + '[' + item.exten + ']'"
                        :value="item._id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('intelligentQualityCheck.intelQualityRule')+':'">
                    <el-select size="mini" multiple v-model="webChatform.ruleId" collapse-tags>
                      <el-option
                        v-for="(item, index) in qualityRuleWebList"
                        :disabled="item._id!==''&&webChatform.ruleId.indexOf('')!==-1"
                        :key="index"
                        :label="item.name"
                        :value="item._id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item :label="$t('intelligentQualityCheck.intelTaskQuality')+':'">
                    <el-select size="mini" v-model="webChatform.taskId" multiple collapse-tags>
                      <el-option
                        v-for="(item, index) in qualityWebChatTaskList"
                        :disabled="item._id!==''&&webChatform.taskId.indexOf('')!==-1"
                        :key="index"
                        :label="item.name"
                        :value="item._id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('intelligentQualityCheck.intelGradeNum')+':'">
                    <el-input size="mini" v-model.trim="webChatform.gradeAmountStart" style="width: calc(50% - 30px)">
                    </el-input>
                    <span class="line"></span>
                    <el-input size="mini" v-model.trim="webChatform.gradeAmountEnd" style="width: calc(50% - 30px)">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('public.queues')+':'">
                    <el-select size="mini" v-model.trim="webChatform.toPeer" multiple filterable :placeholder="$t('qualityCheck.skillGroupSearch')">
                      <el-option
                        v-for="(item, index) in webchatQueueList"
                        :key="index"
                        :label="item.DisplayName"
                        :value="item.Exten">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('public.customerName')+':'">
                    <el-input size="mini" v-model.trim="webChatform.sName" :placeholder="$t('public.pleaseEnter')"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <!-- 会话ID -->
                <el-col :span="6">
                  <el-form-item :label="$t('qualityCheck.sessionId')">
                    <el-input size="mini" v-model.trim="webChatform._id" :placeholder="$t('public.pleaseEnter')"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <!--质检任务-->
          <div v-show="taskIsShow">
            <el-form labelPosition="top" :inline="true" :model="taskform" ref="taskform"  class="task-form-inline form-inline">
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item :label="$t('intelligentQualityCheck.intelQualityTime')+':'">
                    <el-date-picker size="mini"
                          :id="['z3','z4']"
                          v-model="taskform.time"
                          :editable="boolean"
                          type="datetimerange"
                          :picker-options="pickerOptions"
                          :placeholder="$t('public.timeRanges')"
                          align="right"
                          @change="qualityTime">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('intelligentQualityCheck.intelQualityAgents')+':'">
                    <el-popover
                      ref="popover6"
                      placement="bottom"
                      @show="popoverShow"
                      width="240"
                      trigger="click">
                      <agent-tree :readSeat="taskFolllowedAgents" ref="agentTree" @saveFollowedAgents="saveTaskFollowedAgents"></agent-tree>
                    </el-popover>
                    <div class="follow-agent-wrap" style="width: calc(100% - 16px)" v-popover:popover6>
                        <span class="follow-agent follow-common" v-for="item in taskFolllowedAgents" :key="item._id">{{item.label}}
                          <i class="el-icon-close" @click.stop="closeTaskFollowedAgents(item._id)"></i>
                        </span>
                      <div>
                        <span type="primary" class="follow-agent-wrap-btn"><i class="el-icon-arrow-down" style="color: #c0c4cc"></i></span>
                      </div>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="$t('intelligentQualityCheck.intelTypeOfQuality')+':'">
                    <el-select size="mini" v-model="taskform.qualityType">
                      <el-option
                        v-for="(item, index) in qualityTypeList"
                        :key="index"
                        :label="item.name"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
      </affix>
      <div class="submit">
        <el-button class="primary_btn" @click="rest">{{$t('public.reset')}}</el-button>
        <el-button type="primary" class="search primary_btn" @click="queryList">{{$t('public.search2')}}</el-button>
      </div>
      <affix :label="$t('public.searchResult')" style="padding: 8px 20px 0;"></affix>
      <callDetails :callDialogShow="callDialogShow" v-if="callDetailsIsShow"
                   @close="off" :flagId="flagId" :reGrade="true"
                   :currentItemCall = "currentItemCall"
                   :currentGrade = "currentGrade"  :template = "this.template"
                   :ruleRender="ruleRender"
                   @saveGrade="saveGrade" :qcResectLabel="qcResectLabel" @off="off"
                   @handle="handle" :refreshCallGrade="refreshCallGrade" :disabled="lookGrade"
                   @checkResultFun="checkResultFun"
                   @channelFun="callDetaillChannel" @giveUpResult="giveUpCallResult"></callDetails>
      <webChatDetails :webchatDialogShow="webchatDialogShow" v-if="webChatDetailsIsShow"
                      @close="off" :reGrade="true" :currentGrade = "currentGrade"
                      @channelFun="webDetailChannel"
                      :currentItemSny = "currentItemWebChat" @off="off" @handle="handle"
                      @saveGrade="saveGrade" @giveUpResult="giveUpWebResult" @checkResultFun="checkResultFun"></webChatDetails>
      <div v-show="callIsShow" class="quality-check-realust-table">
        <div class="btn-wrap">
          <el-popover
            placement="top"
            width="160"
            v-model="popoverIsShow">
            <div v-show="surePopover">
              <p>{{$t('intelligentQualityCheck.intelSurePopoverContent')}}</p>
              <div style="text-align: right; margin: 5px">
                <el-button size="mini" type="text" @click="popoverIsShow = false">{{$t('public.cancel')}}</el-button>
                <el-button type="primary" size="mini" @click="sureGiveUpResult">{{$t('public.confirm')}}</el-button>
              </div>
            </div>
            <div v-show="sureNoPopover">
              <p>{{$t('intelligentQualityCheck.intelSureNoPopoverContent')}}</p>
              <div style="text-align: right; margin: 5px">
                <el-button size="mini" type="text" @click="popoverIsShow = false">{{$t('public.Iknow')}}</el-button>
              </div>
            </div>
            <el-button slot="reference" class="primary_btn deploy-btn" @click="giveUpResult">{{$t('intelligentQualityCheck.intelGiveUpResult')}}</el-button>
          </el-popover>
          <el-button class="primary_btn deploy-btn" @click="reportExcel" style="margin-left: 10px">{{$t('sms.exportExcel')}}</el-button>
        </div>
        <div class="deploy">
          <div class="search-pagination">
            <pagination
              :small="paginationRecordCall.small"
              :currentPage="paginationRecordCall.currentPage"
              :count="countRecord"
              @turnPage="turnPageRecordCall"
              :totalPage="totalPageRecord"
            >
            </pagination>
          </div>
        </div>
         <qualityCheckResultTable :tableData="callTable" :options="callOptions" :callFlag="true" @listenVideo="listenVideo" @handleSelectionChange="selectionChangeFun" @details="callDetailsFun"></qualityCheckResultTable>
      </div>
      <div v-show="webChatIsShow" class="quality-check-realust-table">
        <div class="btn-wrap">
          <el-popover
            placement="top"
            width="160"
            v-model="popoverWebIsShow">
            <div v-show="surePopover">
              <p>{{$t('intelligentQualityCheck.intelSurePopoverContent')}}</p>
              <div style="text-align: right; margin: 5px">
                <el-button size="mini" type="text" @click="popoverWebIsShow = false">{{$t('public.cancel')}}</el-button>
                <el-button type="primary" size="mini" @click="sureGiveUpResult">{{$t('public.confirm')}}</el-button>
              </div>
            </div>
            <div v-show="sureNoPopover">
              <p>{{$t('intelligentQualityCheck.intelSureNoPopoverContent')}}</p>
              <div style="text-align: right; margin: 5px">
                <el-button size="mini" type="text" @click="popoverWebIsShow = false">{{$t('public.Iknow')}}</el-button>
              </div>
            </div>
            <el-button slot="reference" class="primary_btn deploy-btn" @click="giveUpResult">{{$t('intelligentQualityCheck.intelGiveUpResult')}}</el-button>
          </el-popover>
          <el-button class="primary_btn deploy-btn" @click="reportExcel" style="margin-left: 10px">{{$t('sms.exportExcel')}}</el-button>
        </div>
        <div class="deploy">
          <div class="search-pagination">
            <pagination
              :small="paginationRecordWeb.small"
              :currentPage="paginationRecordWeb.currentPage"
              :count="countRecord"
              @turnPage="turnPageRecordWeb"
              :totalPage="totalPageRecord"
            >
            </pagination>
          </div>
        </div>
        <qualityCheckResultTable :tableData="webChatTable" :options="webChatOptions" :callFlag="false" @handleSelectionChange="selectionChangeFun" @details="webDetailsFun"></qualityCheckResultTable>
      </div>
      <div v-show="taskIsShow" class="quality-check-realust-table">
        <div class="deploy">
          <div class="search-pagination">
            <pagination
              :small="paginationRecordTask.small"
              :currentPage="paginationRecordTask.currentPage"
              :count="taskCountRecord"
              @turnPage="turnPageRecordTask"
              :totalPage="taskTotalPageRecord"
            >
            </pagination>
          </div>
        </div>
        <qualityCheckResultTaskTable :tableData="taskTable" :webChatOptions="webChatOptions" :callOptions="callOptions" @details="taskWebDetails" @listenVideo="taskListenVideo" @exportTaskResult="exportTaskResultBtn"></qualityCheckResultTaskTable>
      </div>
      <el-dialog modal-append-to-body lock-scroll top="10%" :visible.sync="isLis" :title="$t('qualityCheck.ListenToTheRecording')" @close="offAudio" @open="openAudio">
        <OldAudioCommon v-if="showOld" flagId="inteligent_result_listen_old" :srcUrl="audioListen" :refreshAudio="refreshAudio" :isShowAudioDownload="false" :isShowSubmitAudio="false" :currentObj="{}" :pauseAudio="pauseAudio"></OldAudioCommon>
        <AudioCommon v-if="!showOld" flagId="inteligent_result_listen" @showOldAudio="showOldAudio" callStatus='dealing' :srcUrl="audioListen" :refreshAudio="refreshAudio" :isShowAudioDownload="false" :isShowSubmitAudio="false" :currentObj="{}" :pauseAudio="pauseAudio"></AudioCommon>
      </el-dialog>
    </div>
</template>

<script>
    import affix from '../../../ui-modules/affix/Affix'
    import AgentTree from '../../qualityCheck/base/qualityAgentTree'
    import qualityCheckResultTable from '../qualityTable/qualityCheckResultTable'
    import qualityCheckResultTaskTable from '../qualityTable/qualityCheckResultTaskTable'
    import Pagination from '@/components/public-modules/card/Pagination'
    import * as webchatUtils from '@utils/webchat.js'
    import callDetails from './qualityCheckResultCallDetails'
    import webChatDetails from './qualityCheckResultWebChatDetails'
    import AudioCommon from '@/components/public-modules/audio'
    import OldAudioCommon from '@/components/public-modules/audio/audio.vue'
    import bus from '@/store/eventBus'
    import {checkform} from '@/utils/validate'
    import {deepClone, m7Language, scopeAgents, getCache, getDateTime, getCacheByKey, checkHideTel, updateAllOptions, initFinishName} from '@/utils/m7Utils'
    export default {
      name: 'qualityCheckResultAll',
      data () {
        return {
          showOld: false,
          pauseAudio: 'open',
          isShow: true,
          isShowCon: false,
          popoverIsShow: false, // 弹框显示隐藏
          surePopover: true,
          sureNoPopover: false,
          popoverWebIsShow: false,
          popoverContent: '', // 弹框内容
          boolean: false,
          templateTitle: 'callTemplate', // 3个模板名称
          callIsShow: true, // 通话展示
          webChatIsShow: false, // 在线咨询展示
          taskIsShow: false, // 质检任务展示
          webOrCallOrTaskTemp: 1, // 模板选择
          callForm: { // 通话表单
            callTime: '', // 通话时长
            callType: [], // 呼叫类型
            agentId: '', // 通话座席
            fromCid: '', // 主叫号码
            fromDid: '', // 被叫号码
//            satisfaction: '', // 满意度
            BEGIN_TIME: '',
            END_TIME: '',
            callTimeLengthStart: '', // 通话时长开始
            callTimeLengthEnd: '', // 通话时长结束
            gradeUser: [], // 质检人员
            toPeer: [], // 技能组
            ruleId: [], // 质检规则
            taskId: [], // 质检任务
            callGetGrade: '', // 质检得分
            gradeAmountStart: '', // 质检得分开始
            gradeAmountEnd: '', // 质检得分结束
            _id:'',//通话编号
          },
          investigateArray: [],//  二级满意度数据
          INVESTIGATE: [],  //  二级满意度条件
          closeOptions: [],
          sessionOptions: [],
          activeFinish: [],
          webChatform: { // 在线咨询表单
            user: '', // 通话座席
            finishKey: '', // 结束会话类型
            appraiseKey: '', // 满意度
            platform: '', // 平台来源
            checkTime: '', // 领取时间
            msgCountType: '', // 消息条数类型
            msgCount: '', // 消息条数
            gradeUser: [], // 质检人员
            ruleId: [], // 质检规则
            beginTimeStart: '',
            beginTimeEnd: '',
            taskId: [], // 质检任务
            gradeAmountStart: '', // 质检得分开始
            gradeAmountEnd: '', // 质检得分结束
            sName:'',//客户名称
            _id:'',//会话ID
          },
          taskform: { // 质检任务表单
            time: '', // 质检时间
            createTimeStart: '', // 开始时间
            createTimeEnd: '', // 结束时间
            gradeUser: '', // 质检座席
            qualityType: '' // 质检类型
          },
          queueList: '', // 技能组
          webchatQueueList: '', // 在线技能组
//          satisfactionList: [], // 满意度
          callAgentList: [], // 质检人员
          pickerOptions: { // 呼入时长
            shortcuts: [{
              text: this.$t('sms.thisOneWeek'),
              onClick (picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                picker.$emit('pick', [start, end])
              }
            }, {
              text: this.$t('sms.thisOneMonth'),
              onClick (picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                picker.$emit('pick', [start, end])
              }
            }, {
              text: this.$t('sms.thisThreeMonth'),
              onClick (picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                picker.$emit('pick', [start, end])
              }
            }]
          },
          callTypeList: [], // 通话类型
          finishReasonList: [], // 结束会话类型
          appraiseList: [], // 满意度
          platforms: [ // 平台来源
            {label: this.$t('webchat.websiteCon'), value: 'pc'},
            {label: this.$t('webchat.wapCon'), value: 'wap'},
            {label: this.$t('webchat.appCon'), value: 'sdk'},
            {label: this.$t('webchat.weChatCon'), value: 'weixin'},
            {label: this.$t('webchat.weChatMini'), value: 'wxmini'},
            {label: this.$t('webchat.weBoCon'), value: 'weibo'},
            {label: this.$t('webchat.enterpriseShot'), value: 'wxwork'},
            {label: this.$t('webchat.baiduBCP'), value: 'ocpc'},
            {label: this.$t('webchat.TikTok'), value: 'dy'},
            {label: this.$t('webchat.platformWXKF'), value: 'wxkf'}
          ],
          qualityRuleList: [], // 质检规则列表数据
          qualityRuleWebList: [],
          qualityCallTaskList: [], // 质检任务通话列表数据
          qualityWebChatTaskList: [], // 质检任务在线列表数据
          callGetGradeList: [], // 通话质检得分类型
          qualityTypeList: [], // 任务下的质检类型数据
          callTable: [], // 通话表格
          taskOptions: [], // 任务表头
          taskTableChildData: [], // 任务子表格
          callOptions: [ // 通话表格表头
            {displayname: this.$t('qualityCheck.callingNumber'), name: 'fromCid'},
            {displayname: this.$t('qualityCheck.calledNumber'), name: 'fromDid'},
            {displayname: this.$t('qualityCheck.callAgent'), name: 'callAgent'},
            {displayname: this.$t('public.queues'), name: 'toPeer'},
            {displayname: this.$t('public.satisfaction'), name: 'INVESTIGATE_show'},
            {displayname: this.$t('qualityCheck.qualityControlPersonnel'), name: 'gradeUser'},
            {displayname: this.$t('intelligentQualityCheck.intelMatchRule'), name: 'ruleName'},
            {displayname: this.$t('intelligentQualityCheck.intelTaskQuality'), name: 'taskName'},
            {displayname: this.$t('intelligentQualityCheck.intelGradeNum'), name: 'gradeAmount'},
            {displayname: this.$t('intelligentQualityCheck.intelGradeDetail'), name: 'comment'},
            {displayname: this.$t('call.callNumber'), name: '_id'},
          ],
          webChatTable: [], // 在线表格
          webChatOptions: [ // 在线表格表头
            {displayname: this.$t('public.locationCustomer'), name: 'custName_show'},
            {displayname: this.$t('public.disposeAgent'), name: 'user'},
            {displayname: this.$t('webchat.claimTime'), name: 'beginTime'},
            {displayname: this.$t('call.skillsGrouop'), name: 'toPeer'},
            {displayname: this.$t('qualityCheck.qualityControlPersonnel'), name: 'gradeUser'},
            {displayname: this.$t('intelligentQualityCheck.intelMatchRule'), name: 'webChatRuleName'},
            {displayname: this.$t('intelligentQualityCheck.intelTaskQuality'), name: 'taskName'},
            {displayname: this.$t('intelligentQualityCheck.intelGradeNum'), name: 'gradeAmount'},
            {displayname: this.$t('intelligentQualityCheck.intelGradeDetail'), name: 'comment'}
          ],
          taskTable: [],    //    任务表格
          paginationRecordCall: { // 通话分页参数
            small: false,
            currentPage: 1
          },
          paginationRecordWeb: { // 在线分页参数
            small: false,
            currentPage: 1
          },
          paginationRecordTask: { // 任务分页参数
            small: false,
            currentPage: 1
          },
          countRecord: 0, // 总数
          totalPageRecord: 0, // 当前页
          taskTotalPageRecord: 0, // 因质检任务中，放弃质检之后，会查在线的list和任务的list,都是totalPageRecord，存在异步二次赋值问题，所以需要分开
          taskCountRecord: 0, // 因质检任务中，放弃质检之后，会查在线的list和任务的list,countRecord，存在异步二次赋值问题，所以需要分开
          selectionData: [], // 被选中的值
          callDialogShow: false, // 通话详情弹框
          flagId: 'result', // 详情弹框类型判断
          currentGrade: {}, // 当前评分
          template: {},
          callDetailsIsShow: false, // 通话详情展示
          webChatDetailsIsShow: false, // 在线详情是否展示
          qcResectLabel: false,
          refreshCallGrade: 0,
          lookGrade: false,
          currentItemCall: {}, // 通话详情数据
          currentItemWebChat: {}, // 在线详情数据
          webchatDialogShow: false, // 在线详情弹框
          finishOptions: {},          //  在线结束会话类型列表
          refreshAudio: 0,
          ruleRender: [],
          audioListen: '', // 听取录音地址
          checkBoxIsTrue: false, // 是否是手动评分
          isLis: false, // 听取录音弹框
          popoverVisableCall: false,    //  座席组件展开时  触发reset方法
          popoverVisableWeb: false,    //  座席组件展开时  触发reset方法
          popoverVisableTask: false,    //  座席组件展开时  触发reset方法
        }
      },
      methods: {
        showOldAudio (curr) {
          this.showOld = curr
        },
        isFold (bool) {
          this.isShowCon = bool
        },
        tempStateChange (val) {
          if (val === 1) { // 模板为通话时
            this.paginationRecordCall.currentPage = 1
            this.callIsShow = true
            this.webChatIsShow = false
            this.taskIsShow = false
            this.templateTitle = 'callTemplate'
            this.queryCallResult(1)
          } else if (val === 2) { // 模板为在线咨询时
            this.paginationRecordWeb.currentPage = 1
            this.callIsShow = false
            this.webChatIsShow = true
            this.taskIsShow = false
            this.templateTitle = 'webTemplate'
            this.queryWebResult(1)
          } else if (val === 3) { // 模板为质检任务时
            this.paginationRecordTask.currentPage = 1
            this.callIsShow = false
            this.webChatIsShow = false
            this.taskIsShow = true
            this.templateTitle = 'taskTemplate'
            this.queryTaskResult(1)
          }
        },
        renderCallTemplate () { // 渲染通话条件模板
          let self = this
          // 通话类型数据 start
          this.$store.dispatch('getCache', {type: 'callType'}).then((res) => {
            let callTypeListData = deepClone(res)
            callTypeListData = callTypeListData.filter(item => {
              item.code_name = m7Language('globalChineseKey.' + item.code_name, null, true) || item.code_name
              return item
            })
            self.callTypeList = callTypeListData
          })
          // 通话类型数据 end
          // 通话技能组数据 start
          this.$store.dispatch('getCache', {type: 'queues'}).then((res) => {
            self.queueList = res
          })
          // 通话技能组数据 end
          // 满意度数据 start
//          this.$store.dispatch('getCache', {type: 'options'}).then((res) => {
//            let _dics = []
//            for (let i = 0; i < res.length; i++) {
//              var obj = res[i]
//              if (obj.name && obj.name === '满意度调查选项') {
//                _dics = obj.options || []
//                break
//              }
//            }
//            let satisfactionList = []
//            for (var n = 0; n < _dics.length; n++) {
//              if (_dics[n] && _dics[n].name && _dics[n].options[0]) {
//                satisfactionList.push({name: _dics[n].name, value: _dics[n].options[0].name})
//              }
//            }
//            console.log(satisfactionList)
//            self.satisfactionList = satisfactionList
//          })
          //   二级满意度
          this.$store.dispatch('getCache', {type: 'investigate'}).then((res) => {
            let arrFirst = [{label: this.$t('public.all'), value: ''},{label: this.$t('public.unevaluated'), value: 'unevaluated'}]
            this.investigateArray = generateNewKeyValue(res, ['name', 'value', 'children'], ['label', 'value', 'children'], arrFirst)
          })
          // 满意度数据 end
          // 质检人员 start
          this.$store.dispatch('getCache', {type: 'agents'}).then((res) => {
            let agents = scopeAgents('qc', res)
            agents.forEach((item) => {
              item.labelCall = item.displayName + '【' + item.exten + '】'
            })
            self.callAgentList = agents
            self.agentList = agents
          })
          // 质检人员 end
          // 质检任务 start
          this.$store.dispatch('getIntelligentQualityCheckResultAllTasklist', {type: 'call'}).then(res => {
            this.qualityCallTaskList = res.data
            this.qualityCallTaskList.unshift({name: this.$t('qualityCheck.all'), _id: ''})
          })
          // 质检任务 end
          // 质检规则 start
          this.$store.dispatch('getRuleLessList', {type: 'call'}).then((res) => {
            this.qualityRuleList = res.data
            this.qualityRuleList.unshift({name: this.$t('qualityCheck.all'), _id: ''})
          })
          // 质检规则 end
          let data = {
            page: 1,
            pageSize: 200
          }
          // 渲染质检辅助信息
          this.$store.dispatch('getMarkRuleListConfig', data).then(res => {
            if (res.success) {
              res.data = res.data.filter((item) => {
                return item.type === 'call' && item.isEnable
              })
              this.ruleRender = deepClone(res.data)
            }
          })
        },
        renderWebChatTemplate () { // 渲染在线咨询条件模板
          let self = this
          // 结束类型 start
          this.$store.dispatch('getCache', {type: 'channelDic'}).then((dics) => {
            let _dics = []
            for (var i = 0; i < dics.length; i++) {
              let obj = dics[i]
              if (obj.type === 'webchat') {
                _dics = obj.options || []
                break
              }
            }
            for (var j = 0; j < dics.length; j++) {
              let obj = dics[j]
              if (obj.type === 'webchatCSR') {
                self.appraiseList = obj.options || []
                break
              }
            }
            this.finishOptions = initFinishName(_dics, {})
            let finishKeys = []
            updateAllOptions(_dics, {Arr: this.sessionOptions})
            this.closeOptions = [
              {label: this.$t('webchat.webchatAll'), value: ''}, ...this.sessionOptions,
              {label: this.$t('webchat.addBlack'), value: 'add_black'}
            ]
          })
          // 结束类型 end
          // 满意度 start
          // this.$store.dispatch('getCache', {type: 'channelDic'}).then((dics) => {
          //   for (var i = 0; i < dics.length; i++) {
          //     let obj = dics[i]
          //     if (obj.type === 'webchatCSR') {
          //       self.appraiseList = obj.options || []
          //       break
          //     }
          //   }
          // })
          // 满意度 end
//          在线技能组
          this.$store.dispatch('getCache', {type: 'mailQueues'}).then((res) => {
            this.webchatQueueList = res
          })
          // 质检规则 start
          this.$store.dispatch('getRuleLessList', {type: 'webchat'}).then((res) => {
            this.qualityRuleWebList = res.data
            this.qualityRuleWebList.unshift({name: this.$t('qualityCheck.all'), _id: ''})
          })
          // 质检规则 end
          // 质检任务 start
          this.$store.dispatch('getIntelligentQualityCheckResultAllTasklist', {type: 'webchat'}).then(res => {
            this.qualityWebChatTaskList = res.data
            this.qualityWebChatTaskList.unshift({name: this.$t('qualityCheck.all'), _id: ''})
          })
          // 质检任务 end
        },
        renderTaskTemplate () { // 渲染任务条件模板
          // let self = this
          // 质检人员 start
          // this.$store.dispatch('getCache', {type: 'agents'}).then((res) => {
          //   let agents = scopeAgents('qc', res)
          //   agents.forEach((item) => {
          //     item.labelCall = item.displayName + '【' + item.exten + '】'
          //   })
          //   self.callAgentList = agents
          //   self.agentList = agents
          // })
          // // 质检人员 end
          // 质检类型 start
          this.qualityTypeList = [
            {name: this.$t('qualityCheck.all'), value: ''},
            {name: this.$t('report.quaCallQuality'), value: 'call'},
            {name: this.$t('intelligentQualityCheck.intelWebchatQuality'), value: 'webchat'}
          ]
          // 质检类型 end
        },
        closeFollowedAgents (agent) { // 技能组
          this.callForm.agentId = this.callForm.agentId.filter((item) => item !== agent)
        },
        closeWebFollowedAgents (agent) { // 技能组
          this.webChatform.user = this.webChatform.user.filter((item) => item !== agent)
        },
        closeTaskFollowedAgents (agent) { // 技能组
          this.taskform.gradeUser = this.taskform.gradeUser.filter((item) => item !== agent)
        },
        popoverShow () { // 通话座席展示
          this.$refs.agentTree.setCheckedKeys()
        },
        //通话坐席保存
        saveFollowedAgents (agents) {
          this.callForm.agentId = deepClone(agents)
          document.getElementsByTagName('body')[0].click()
        },
        //在线坐席保存
        saveWebFollowedAgents (agents) {
          this.webChatform.user = deepClone(agents)
          document.getElementsByTagName('body')[0].click()
        },
        //质检任务坐席保存
        saveTaskFollowedAgents (agents) {
          this.taskform.gradeUser = deepClone(agents)
          document.getElementsByTagName('body')[0].click()
        },
        callTimeChange (value) { // 通话时长
          if (!value) {
            this.callForm.callTime = ''
            this.callForm.offringTimeStart = ''
            this.callForm.offringTimeEnd = ''
          }
        },
        rest () { // 重置
          if (this.templateTitle === 'callTemplate') {
            for (let i in this.callForm) {
              if (typeof this.callForm[i] === 'object' && i !== 'callTime' && i !== 'GRADE_TIME' && i !== 'SUBMITTED_TIME') {
                this.callForm[i] = []
              } else {
                this.callForm[i] = ''
              }
            }
            this.INVESTIGATE = []
          } else if (this.templateTitle === 'webTemplate') {
            for (let i in this.webChatform) {
              if (typeof this.webChatform[i] === 'object' && i !== 'callTime' && i !== 'GRADE_TIME' && i !== 'SUBMITTED_TIME') {
                this.webChatform[i] = []
              } else {
                this.webChatform[i] = ''
              }
            }
            this.$refs.agentTree.setCheckedKeys()
            this.activeFinish = ''
          } else if (this.templateTitle === 'taskTemplate') {
            for (let i in this.taskform) {
              if (typeof this.taskform[i] === 'object' && i !== 'callTime' && i !== 'GRADE_TIME' && i !== 'SUBMITTED_TIME') {
                this.taskform[i] = []
              } else {
                this.taskform[i] = ''
              }
            }
          }
        },
        queryList () {
          if (this.templateTitle === 'callTemplate') {
            this.paginationRecordCall.currentPage = 1
          } else if (this.templateTitle === 'webTemplate') { // 模板为在线
            this.paginationRecordWeb.currentPage = 1
          } else if (this.templateTitle === 'taskTemplate') { // 模板为任务
            this.paginationRecordTask.currentPage = 1
          }
          this.query()
        },
        //   查询
        query () { // 查询按钮
          if (this.templateTitle === 'callTemplate') { // 模板为通话
            if (this.callForm.gradeAmountStart !== '' || this.callForm.gradeAmountEnd !== '') {
              let match = checkform(this.callForm.gradeAmountStart, 'Number2')
              let match1 = checkform(this.callForm.gradeAmountEnd, 'Number2')
              if (parseFloat(this.callForm.gradeAmountStart) > 100 || parseFloat(this.callForm.gradeAmountEnd) > 100) {
                this.$message.error(this.$t('intelligentQualityCheck.intelGradeThanMax'))
              }
              if (match || match1) {
                this.$message({
                  type: 'error',
                  message: this.$t('intelligentQualityCheck.intelTestNum')
                })
                return false
              }
            }
            this.queryCallResult(this.paginationRecordCall.currentPage)
          } else if (this.templateTitle === 'webTemplate') { // 模板为在线
            if (this.webChatform.gradeAmountStart !== '' || this.webChatform.gradeAmountEnd !== '') {
              let test = checkform(this.webChatform.gradeAmountStart, 'Number2')
              let test1 = checkform(this.webChatform.gradeAmountEnd, 'Number2')
              if (parseFloat(this.webChatform.gradeAmountStart) > 100 || parseFloat(this.webChatform.gradeAmountEnd) > 100) {
                this.$message.error(this.$t('intelligentQualityCheck.intelGradeThanMax'))
              }
              if (test || test1) {
                this.$message({
                  type: 'error',
                  message: this.$t('intelligentQualityCheck.intelTestNum')
                })
                return false
              }
            }
            this.queryWebResult(this.paginationRecordWeb.currentPage)
          } else if (this.templateTitle === 'taskTemplate') { // 模板为任务
            this.queryTaskResult(this.paginationRecordTask.currentPage)
          }
        },
        queryCallResult (page) { // 查询通话结果
          let agents = this.$store.getters.agents || {}
          if (this.callForm.callTime && this.callForm.callTime[0] !== null) {
            this.callForm.offringTimeStart = getDateTime(this.callForm.callTime[0])
          }
          if (this.callForm.callTime && this.callForm.callTime[1] !== null) {
            this.callForm.offringTimeEnd = getDateTime(this.callForm.callTime[1])
          }
          if(this.callForm.ruleId.indexOf('')!==-1){
            this.callForm.ruleId = []
          }
          if(this.callForm.taskId.indexOf('')!==-1){
            this.callForm.taskId = []
          }
          let data = {page: page, limit: 10}
          data.query = deepClone(this.callForm)
          delete data.query.callTime
          this.$store.dispatch('queryIntelligentQualityCheckResultAllList', data).then((res) => {
            // this.callOptions = res.tableHeader.Config
            this.totalPageRecord = Math.ceil(res.count / 10) || 0
            this.countRecord = res.count
            let ruleName = ''
            const list = res.data || []
            if (list.length === 0) {
              if (!res.count) {
                // 第一页且count为0是不再发请求
                this.paginationRecordCall.currentPage = 1
              } else {
                let page = Math.ceil(res.count / data.limit)
                this.paginationRecordCall.currentPage = page
                this.queryCallResult(page)
                return false
              }
            }
            list.map((item, index) => {
              if (agents[item.agentId]) {
                item.callAgent = agents[item.agentId].displayName // 通话座席
              } else {
                item.callAgent = '--'
              }
              if (agents[item.gradeUser]) {
                item.gradeUser = agents[item.gradeUser].displayName // 质检人员
              } else {
                item.gradeUser = '--'
              }
              if (!item.toPeer) {
                item.toPeer = '--'
              }
              if (!item.taskName) {
                item.taskName = '--'
              }
              if (item.type === 'manual') { // 判断是否是智能质检
                item.ruleName = '--'
              } else {
                item.ruleResults.forEach(ruleItem => {
                  ruleName += ruleItem.name + ','
                })
                item.ruleName = ruleName.substr(0, ruleName.length - 1)
                ruleName = ''
              }
              if (item.callType === 'dialout' || item.callType === 'dialTransfer') {
                item.fromDid = checkHideTel(item.fromDid, this.$store.state.session.user)  //   被叫号码
              } else {
                item.fromCid = checkHideTel(item.fromCid, this.$store.state.session.user)    //   主叫号码
              }
              // 二级满意度
              item.INVESTIGATE_show = ''
              if (item.INVESTIGATE || item.INVESTIGATE === 0) {
                for (let n = 0; n < this.investigateArray.length; n++) {
                  if (this.investigateArray[n].value === item.INVESTIGATE) {
                    item.INVESTIGATE_show = this.investigateArray[n].label || ''
                    if (item.CHILD_INVESTIGATE || item.CHILD_INVESTIGATE === 0) {
                      if (this.investigateArray[n].children.length > 0) {
                        this.investigateArray[n].children.forEach(one => {
                          if (one.value === item.CHILD_INVESTIGATE) {
                            item.INVESTIGATE_show = item.INVESTIGATE_show + '/' + one.label
                          }
                        })
                      }
                    }
                    break
                  }
                }
              }
            })
            this.callTable = list
          })
        },
        listenVideo (val) { // 听取录音
          this.$store.dispatch('recordListenLog', {CALL_SHEET_ID: val._id}).then((res) => {
            this.isLis = true
            this.audioListen = val.path
            this.refreshAudio = Math.random()
          })
        },
        offAudio () { // 关闭录音
          let play = document.getElementById('quality-autoplay_inteligent_result_listen_old')
          if (play) {
            play.pause()
          }
          this.pauseAudio = 'close'
        },
        openAudio () {
          this.pauseAudio = 'open'
        },
        callDetailsFun (data) { // 进入详情
          this.callDialogShow = true
          this.qcResectLabel = true
          let self = this
          if (data.REPEAT_CALL) {
            data.repeatCall = data.REPEAT_CALL === '48h' ? this.$t('call.repeatCall48h') : this.$t('call.repeatCall24h')
          } else {
            data.repeatCall = '--'
          }
          this.$store.dispatch('IntelligentQualityCheckResultAllDetails', data._id).then((response) => {
            this.$store.dispatch('queryBusiness', {callId: data._id, customer: data.CUSTOMER_ID}).then((res) => {
              this.recordFileName(response.fileServer, response.recordFileName, response.PBX, function (url) {
                response.audio = url
                if (res && res.length > 0) {
                  response.busHistory = [res[0]]
                } else {
                  response.busHistory = []
                }
                if (response && response.ruleResults) {
                  let nomalScore = 0
                  response.ruleResults.map(item => {
                    item.hitCount = '共' + item.hitCount + '次命中'
                    if (!item.isCanceled) {
                      nomalScore += Number(item.scoreItem.split(',')[1])
                    }
                  })
                  response.nomalScore = response.gradeAmount - nomalScore
                }
                self.currentItemCall = response
                if (self.currentItemCall.satisfaction === '1') {
                  self.currentItemCall.satisfaction = self.$t('intelligentQualityCheck.intelSatisfied')
                } else if (self.currentItemCall.satisfaction === '2') {
                  self.currentItemCall.satisfaction = self.$t('intelligentQualityCheck.intelDissatisfied')
                }
                self.refreshCallGrade = Math.random()
                self.callDetailsIsShow = true
                self.webChatDetailsIsShow = false
                bus.$emit('intelQualityEnterCallDeltails')
              })
            })
          })
        },
        callDetaillChannel () { // 通话详情取消
          this.callDetailsIsShow = false
        },
        webDetailChannel () {
          this.webChatDetailsIsShow = false
        },
        giveUpCallResult (val) { // 通话详情放弃质检结果
          if (val && val.success) {
            this.$message({
              message: this.$t('intelligentQualityCheck.giveUpQcSuccess'),
              type: 'success'
            })
            this.callDetailsIsShow = false
            this.queryCallResult(this.paginationRecordCall.currentPage)
            if (this.templateTitle === 'taskTemplate') {
              this.queryTaskResult(this.paginationRecordTask.currentPage)
            }
          } else {
            this.$message.error(val.message)
          }
        },
        giveUpWebResult (val) { // 在线详情放弃质检结果
          if (val && val.success) {
            this.$message({
              message: this.$t('intelligentQualityCheck.giveUpQcSuccess'),
              type: 'success'
            })
            this.webChatDetailsIsShow = false
            this.queryWebResult(this.paginationRecordWeb.currentPage)
            if (this.templateTitle === 'taskTemplate') {
              this.queryTaskResult(this.paginationRecordTask.currentPage)
            }
          } else {
            this.$message.error(val.message)
          }
        },
        queryWebResult (page) { // 查询在线结果
          let agents = this.$store.getters.agents || {}
          if (this.webChatform.checkTime && this.webChatform.checkTime[0] !== null) {
            this.webChatform.beginTimeStart = getDateTime(this.webChatform.checkTime[0])
          }
          if (this.webChatform.checkTime && this.webChatform.checkTime[1] !== null) {
            this.webChatform.beginTimeEnd = getDateTime(this.webChatform.checkTime[1])
          }
          let finishArr = this.activeFinish
          if (finishArr && finishArr.length > 0) {
            for (let i = 0; i < finishArr.length; i++) {
              finishArr[i] = finishArr[i].split('__')[0]
              if (finishArr[i] === '') {
                this.webChatform.finishKey = ''
              }
              if (finishArr[i] === 'add_black') {
                this.webChatform.finishKey = 'add_black'
              }
            }
          }
          if(this.webChatform.ruleId.indexOf('')!==-1){
            this.webChatform.ruleId = []
          }
          if(this.webChatform.taskId.indexOf('')!==-1){
            this.webChatform.taskId = []
          }
          this.webChatform.finishKey = finishArr[finishArr.length - 1]
          let data = {}
          data.page = page
          data.limit = 10
          data.query = deepClone(this.webChatform)
          if (data.query.toPeer && data.query.toPeer.length === 0) {
            delete data.query.toPeer
          }
          delete data.query.checkTime
          if(!data.query._id){
            delete data.query._id
          }
          if(!data.query.sName){
            delete data.query.sName
          }
          this.$store.dispatch('queryIntelligentQualityCheckResultAllWebList', data).then((res) => {
            if(res.success){
              this.totalPageRecord = Math.ceil(res.count / 10) || 0
              this.countRecord = res.count
              let webChatRuleName = ''
              const list = res.data || []
              if (list.length === 0) {
                if (!res.count) {
                  // 第一页且count为0是不再发请求
                  this.paginationRecordWeb.currentPage = 1
                } else {
                  let page = Math.ceil(res.count / data.limit)
                  this.paginationRecordWeb.currentPage = page
                  this.queryWebResult(page)
                  return false
                }
              }
              list.map((item, index) => {
                if (agents[item.gradeUser]) {
                  item.gradeUser = agents[item.gradeUser].displayName // 通话座席
                } else {
                  item.gradeUser = '--'
                }
                if (agents[item.user]) {
                  item.user = agents[item.user].displayName // 质检人员
                } else {
                  item.user = '--'
                }
                if (!item.taskName) {
                  item.taskName = '--'
                }
                let toPeerName = ''
                if (getCacheByKey('mailQueues', 'Exten', item.toPeer) != null) { // 技能组
                  toPeerName = getCacheByKey('mailQueues', 'Exten', item.toPeer).DisplayName
                  item.toPeer = toPeerName
                } else {
                  item.toPeer = '--'
                }
                if (item.beginTime == null) { // 会话领取时间
                  item.beginTime = '--'
                }
                if (item.customerName === '') { // 定位客户
                  if (item.sName !== '') {
                    item.custName_show = item.sName
                  } else {
                    item.custName_show = '--'
                  }
                } else {
                  item.custName_show = item.customerName
                }
                if (item.type === 'manual') { // 判断是否是智能质检
                  item.webChatRuleName = '--'
                } else {
                  item.ruleResults.forEach(ruleItem => {
                    webChatRuleName += ruleItem.name + ','
                  })
                  item.webChatRuleName = webChatRuleName.substr(0, webChatRuleName.length - 1)
                  webChatRuleName = ''
                }
              })
              this.webChatTable = list
            }
          })
        },
        queryTaskResult (page) { // 任务查询结果
          let agents = this.$store.getters.agents || {}
          let data = {page: page, limit: 10}
          if (this.taskform.time && this.taskform.time[0] !== null) {
            this.taskform.createTimeStart = getDateTime(this.taskform.time[0])
          }
          if (this.taskform.time && this.taskform.time[1] !== null) {
            this.taskform.createTimeEnd = getDateTime(this.taskform.time[1])
          }
          data.type = this.taskform.qualityType
          data.qcuser = this.taskform.gradeUser
          data.createTimeStart = this.taskform.createTimeStart
          data.createTimeEnd = this.taskform.createTimeEnd
          this.$store.dispatch('getQualityCheckQuaryResultQueryTasks', data).then(res => {
            if (res.success) {
              this.taskTotalPageRecord = Math.ceil(res.count / 10) || 0
              this.taskCountRecord = res.count || 0
              let ruleName = ''
              const list = res.data || []
              if (list.length === 0) {
                if (!res.count) {
                  // 第一页且count为0是不再发请求
                  this.paginationRecordTask.currentPage = 1
                } else {
                  let page = Math.ceil(res.count / data.limit)
                  this.paginationRecordTask.currentPage = page
                  this.queryTaskResult(page)
                  return false
                }
              }
              list.map(item => {
                if (item.rule) {
                  for (var i = 0; i < item.rule.length; i++) {
                    ruleName += item.rule[i].name + ','
                  }
                  item.ruleName = ruleName.substr(0, ruleName.length - 1)
                  ruleName = ''
                }
                if (agents[item.user]) {
                  item.user = agents[item.user].displayName // 通话座席
                } else {
                  item.user = '--'
                }
                if (item.status && item.status !== '') {
                  if (item.status === 'ready') {
                    item.status_show = this.$t('intelligentQualityCheck.intelredeying')
                  } else if (item.status === 'run') {
                    item.status_show = this.$t('business.dealing')
                  } else if (item.status === 'finish') {
                    item.status_show = this.$t('questionnaire.complete')
                  } else if (item.status === 'fail') {
                    item.status_show = this.$t('km.importError')
                  }
                }
                if (item.type === 'webchat') {
                  item.type_show = this.$t('intelligentQualityCheck.intelWebchatQuality')
                } else if (item.type === 'call') {
                  item.type_show = this.$t('report.quaCallQuality')
                }
              })
              this.taskTable = list
            }
          })
        },
        webDetailsFun (data) { // 在线咨询进入详情
          let agents = this.$store.getters.agents || {}
          this.webchatDialogShow = true
          let self = this
          let nomalGrade = 0
          let p1 = this.$store.dispatch('queryBusiness', {linkWebchat: data._id, sid: data.sid})
          let p2 = this.$store.dispatch('IntelligentQualityCheckResultAllWebDetails', data._id)
          let p3 = this.$store.dispatch('popupWebchatById', {_id: data._id, sid: data.sid})
          Promise.all([p1, p2, p3]).then(([response, res, resp]) => {
            self.currentItemWebChat = deepClone(res) || {}
            if (response && response.length > 0) {
              self.currentItemWebChat.busHistory = [response[0]]
            } else {
              self.currentItemWebChat.busHistory = []
            }
            if (resp.row) {
              self.currentItemWebChat.sName = resp.row.name
              self.currentItemWebChat.custName = resp.row.name
            }
            if (res && res.ruleResults) {
              let nomalScore = 0
              res.ruleResults.map(item => {
                item.hitCount = '共' + item.hitCount + '次命中'
                if (!item.isCanceled) {
                  nomalScore += Number(item.scoreItem.split(',')[1])
                }
              })
              res.nomalScore = res.gradeAmount - nomalScore
            }
            if (self.currentItemWebChat.dialogues && self.currentItemWebChat.dialogues.length) {
              self.currentItemWebChat.dialogues.forEach(item => {
                if (item.contentType === 'text') {
                  if (item.showHtml === 'true' || (typeof item.showHtml === 'boolean' && item.showHtml)) {
                    self.$set(item, 'content', item.text)
                  } else {
                    self.$set(item, 'content', webchatUtils.renderEmoji(item.text))
                  }
                } else if (item.contentType === 'file') {
                  self.$set(item, 'fileName', webchatUtils.transferFileContent(item.message))
                }
              })
            }
            if (agents[self.currentItemWebChat.user] && agents[self.currentItemWebChat.user].displayName) {
              self.currentItemWebChat.user = agents[self.currentItemWebChat.user].displayName // 通话座席
            } else {
              self.currentItemWebChat.user = ''
            }
            if (agents[self.currentItemWebChat.gradeUser] && agents[self.currentItemWebChat.gradeUser].displayName) {
              self.currentItemWebChat.gradeUser_show = agents[self.currentItemWebChat.gradeUser].displayName // 通话座席
            } else {
              self.currentItemWebChat.gradeUser_show = ''
            }
            if (res && Number(res.gradeAmount) + nomalGrade > 100) {
              self.currentItemWebChat.nomalGrade = 100
            } else {
              self.currentItemWebChat.nomalGrade = res ? Number(res.gradeAmount) + nomalGrade : 0
            }
            if (self.currentItemWebChat.finishKey) {
              self.currentItemWebChat.finishReasonTitle = this.finishOptions[self.currentItemWebChat.finishKey] || ''
            } else {
              self.currentItemWebChat.finishReasonTitle = ''
            }
            self.webChatDetailsIsShow = true
            self.callDetailsIsShow = false
            bus.$emit('intelQualityEnterWebDeltails')
          })
//          this.$store.dispatch('queryBusiness', {linkWebchat: data._id, sid: data.sid}).then((response) => {
//            if (response && response.length > 0) {
//              data.busHistory = [response[0]]
//            } else {
//              data.busHistory = []
//            }
//            debugger
//            self.currentItemWebChat = data
//          })
//          this.$store.dispatch('IntelligentQualityCheckResultAllWebDetails', data._id).then(res => {
//            debugger
//            if (res.ruleResults) {
//              let nomalScore = 0
//              res.ruleResults.map(item => {
//                item.hitCount = '共' + item.hitCount + '次命中'
//                if (!item.isCanceled) {
//                  nomalScore += Number(item.scoreItem.split(',')[1])
//                }
//              })
//              res.nomalScore = res.gradeAmount - nomalScore
//            }
//            this.$store.dispatch('popupWebchatById', {_id: data._id, sid: data.sid}).then((resp) => {
//              if (resp.row) {
//                self.currentItemWebChat.sName = resp.row.name
//                self.currentItemWebChat.custName = resp.row.name
//              }
//            })
//            self.currentItemWebChat = res
//            if (self.currentItemWebChat.dialogues && self.currentItemWebChat.dialogues.length) {
//              self.currentItemWebChat.dialogues.forEach(item => {
//                if (item.contentType === 'text') {
//                  if (item.showHtml === 'true' || (typeof item.showHtml === 'boolean' && item.showHtml)) {
//                    self.$set(item, 'content', item.text)
//                  } else {
//                    self.$set(item, 'content', webchatUtils.renderEmoji(item.text))
//                  }
//                } else if (item.contentType === 'file') {
//                  self.$set(item, 'fileName', webchatUtils.transferFileContent(item.message))
//                }
//              })
//            }
//            if (agents[self.currentItemWebChat.user] && agents[self.currentItemWebChat.user].displayName) {
//              self.currentItemWebChat.user = agents[self.currentItemWebChat.user].displayName // 通话座席
//            } else {
//              self.currentItemWebChat.user = ''
//            }
//            if (agents[self.currentItemWebChat.gradeUser] && agents[self.currentItemWebChat.gradeUser].displayName) {
//              self.currentItemWebChat.gradeUser_show = agents[self.currentItemWebChat.gradeUser].displayName // 通话座席
//            } else {
//              self.currentItemWebChat.gradeUser_show = ''
//            }
//            if (Number(res.gradeAmount) + nomalGrade > 100) {
//              self.currentItemWebChat.nomalGrade = 100
//            } else {
//              self.currentItemWebChat.nomalGrade = Number(res.gradeAmount) + nomalGrade
//            }
//            self.webChatDetailsIsShow = true
//            self.callDetailsIsShow = false
//            bus.$emit('intelQualityEnterWebDeltails')
//          })
        },
        recordFileName (server, name, pbx, callBack) {
          if (!server) {
            callBack('')
            return
          }
          if (server.indexOf('record.7moor.com') > -1 || server.indexOf('m7-record.oss-cn-hangzhou') > -1 || server.indexOf('aliyuncs.com') > -1) {
            server = 'https' + server.substr(server.indexOf(':'), server.length)
            callBack(server + '/' + name)
          } else if (document.location.protocol === 'https:') {
            if (pbx) {
              getCache('accountPbx', pbx, this, function (pbxObj) {
                if (pbxObj) {
                  if (pbxObj.assDomain) {
                    let assDomain = pbxObj.assDomain
                    if (assDomain.substr(assDomain.length - 1, assDomain.length) === '/') {
                      assDomain = assDomain.substr(0, assDomain.length - 1)
                    }
                    server = assDomain
                  }
                }
                callBack(server + '/' + name)
              })
            } else {
              callBack(server + '/' + name)
            }
          } else {
            callBack(server + '/' + name)
          }
        },
        off () { // 详情关闭
          let play = document.getElementById('quality-autoplay_' + this.flagId + '_old')
          if (play) {
            play.pause()
          }
          this.webchatDialogShow = false
          this.callDialogShow = false
        },
        saveGrade () {
        },
        handle () {},
        giveUpResult () { // 放弃质检结果
          if (this.selectionData.length > 0) {
            this.surePopover = true
            this.sureNoPopover = false
          } else {
            this.surePopover = false
            this.sureNoPopover = true
          }
        },
        sureGiveUpResult () {
          let data = {ids: []}
          this.selectionData.map(item => {
            data.ids.push(item._id)
          })
          let sendAction = ''
          if (this.templateTitle === 'callTemplate') { // 通话模板
            sendAction = 'giveUpQualityCheckesRultAllCall'
          } else if (this.templateTitle === 'webTemplate') { // 在线模板
            sendAction = 'giveUpQualityCheckesRultAllWeb'
          }
          this.$store.dispatch(sendAction, data).then(res => {
            if (res.success && res) {
              this.$message({
                message: this.$t('intelligentQualityCheck.giveUpQcSuccess'),
                type: 'success'
              })
              if (this.templateTitle === 'callTemplate') { // 通话模板
                this.popoverIsShow = false
                this.queryCallResult(this.paginationRecordCall.currentPage)
              } else if (this.templateTitle === 'webTemplate') { // 在线模板
                this.popoverWebIsShow = false
                this.queryWebResult(this.paginationRecordWeb.currentPage)
              }
            }
          })
        },
        exportTaskResultBtn (data) {  // 导出EXCEL
          if (data.type === 'webchat') {
            this.$store.dispatch('exportCdrExcel', {data: {Method: 'exportWebchatAutoqcResultList', Query: {taskId: data._id}}})
          } else {
            this.$store.dispatch('exportCdrExcel', {data: {Method: 'exportCallAutoqcResultList', Query: {taskId: data._id}}})
          }
        },
        reportExcel () { // 导出EXCEL
          if (this.callIsShow === true) {
            this.$store.dispatch('exportCdrExcel', {data: {Method: 'exportCallAutoqcResultList', Query: this.callForm}})
          }
          if (this.webChatIsShow === true) {
            let obj = deepClone(this.webChatform)
            if (obj.toPeer && obj.toPeer.length === 0) {
              delete obj.toPeer
            }
            this.$store.dispatch('exportCdrExcel', {data: {Method: 'exportWebchatAutoqcResultList', Query: obj}})
          }
        },
        selectionChangeFun (val) { // 表格多选选中
          this.selectionData = val
        },
        turnPageRecordCall (pageVal) { // 分页
          this.paginationRecordCall.currentPage = pageVal
          this.queryCallResult(pageVal)
        },
        turnPageRecordWeb (pageVal) { // 分页
          this.paginationRecordWeb.currentPage = pageVal
          this.queryWebResult(pageVal)
        },
        turnPageRecordTask (pageVal) { // 分页
          this.paginationRecordTask.currentPage = pageVal
          this.queryTaskResult(pageVal)
        },
        getTimeChange (value) { // 领取时间
          if (!value) {
            this.webChatform.checkTime = ''
            this.webChatform.beginTimeStart = ''
            this.webChatform.beginTimeEnd = ''
          }
        },
        qualityTime (value) { // 质检时间
          if (!value) {
            this.taskform.time = ''
            this.taskform.createTimeStart = ''
            this.taskform.createTimeEnd = ''
          }
        },
        checkResultFun (val) { // 详情确定
          if (val.success) {
            if (this.templateTitle === 'callTemplate') {
              this.queryCallResult(this.paginationRecordCall.currentPage)
            } else if (this.templateTitle === 'webTemplate') {
              this.queryWebResult(this.paginationRecordWeb.currentPage)
            } else if (this.templateTitle === 'taskTemplate') {
              this.queryTaskResult(this.paginationRecordTask.currentPage)
            }
            this.webchatDialogShow = false
            this.callDialogShow = false
            this.$message({message: this.$t('intelligentQualityCheck.intelGradeSuccess'), type: 'success'})
          }
        },
        taskWebDetails (data, type) { // 任务在线详情
          if (type === 'webchat') {
            this.webDetailsFun(data)
          } else if (type === 'call') {
            this.callDetailsFun(data)
          }
        },
        taskListenVideo (val) { // 任务听录音
          this.listenVideo(val)
        },
        //      二级满意度条件
        changeData (selectValue) {
          console.log(selectValue)
          if (Array.isArray(selectValue)) {
            this.callForm.INVESTIGATE = selectValue[0]
            if (selectValue.length > 1) {
              this.callForm.CHILD_INVESTIGATE = selectValue[1]
            } else {
              this.callForm.CHILD_INVESTIGATE = selectValue[1] = ''
            }
          }
        }
      },
      watch: {
        $route () {
          if (this.$route.params.webOrCallOrTaskTemp) {
            this.webOrCallOrTaskTemp = this.$route.params.webOrCallOrTaskTemp || 1
            this.tempStateChange(this.$route.params.webOrCallOrTaskTemp)
          }
        }
      },
      computed: {
        //通话坐席展示数据
        folllowedAgents () {
          let agents = this.callForm.agentId || []
          let agentsAll = this.$store.getters.agents || {}
          return agents.map((item) => {
            return {_id: item, label: agentsAll[item].displayName}
          })
        },
        //在线坐席展示数据
        webFolllowedAgents () {
          let agents = this.webChatform.user || []
          let agentsAll = this.$store.getters.agents || {}
          return agents.map((item) => {
            return {_id: item, label: agentsAll[item].displayName}
          })
        },
        //质检任务质检坐席展示数据
        taskFolllowedAgents () {
          let agents = this.taskform.gradeUser || []
          let agentsAll = this.$store.getters.agents || {}
          return agents.map((item) => {
            return {_id: item, label: agentsAll[item].displayName}
          })
        }
      },
      beforeMount () {
        this.queryCallResult(1)
        this.renderCallTemplate()
        this.$store.dispatch('getCache', {type: 'mailQueues'})
        this.renderWebChatTemplate() // 调用加载条件模板function
        this.renderTaskTemplate()
        if (this.$route.params.webOrCallOrTaskTemp) {
          this.webOrCallOrTaskTemp = this.$route.params.webOrCallOrTaskTemp || 1
          this.tempStateChange(this.$route.params.webOrCallOrTaskTemp)
        }
      },
      components: {
        affix,
        AgentTree,
        qualityCheckResultTable,
        Pagination,
        qualityCheckResultTaskTable,
        callDetails,
        webChatDetails,
        AudioCommon,
        OldAudioCommon

      }
    }
    function generateNewKeyValue (list, oldKeys, newKeys, label, flag, currentType) { // 数据类型转换
      let result = []
      if (!Array.isArray(list) || !Array.isArray(oldKeys) || !Array.isArray(newKeys) || oldKeys.length !== newKeys.length) {
        return result
      }
      if (Array.isArray(label)) {
      result = deepClone(label)
      } else if (label) {
        result = [{label: label, value: ''}]
      }
      for (let i = 0; i < list.length; i++) {
        let item = {}
        if (flag) {
          list[i].code_name = m7Language('globalChineseKey.' + list[i].code_name, null, true) || list[i].code_name
        }
        for (let j = 0; j < oldKeys.length; j++) {
          let oldKey = oldKeys[j]
          let newKey = newKeys[j]
          // 递归处理多级数据
          if (Array.isArray(list[i][oldKey])) {
            if (list[i][oldKey].length > 0) {
              item[newKey] = generateNewKeyValue(list[i][oldKey], ['name', 'value'], ['label', 'value'])
            }
          } else {
            item[newKey] = list[i][oldKey]
          }
        }
        result.push(item)
      }
      return result
    }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .quality-check-resultAll
    height: calc(100vh - 154px);
    padding: 20px 20px 0;
    overflow: scroll
    .quality-check-realust-table
      margin-bottom 20px
    .form-inline
      margin-top 15px
      .el-form-item
       width 100%
       height 100%
       .el-select, .el-date-editor, .el-input
         width 100%
         height 100%
      .callLength
        width:39%
        height:100%
      .follow-agent-wrap
        float left
        cursor pointer
        width: calc(100% - 17px)
        border-radius: 5px
        border: 1px solid #dcdfe6
        padding: 6px 9px 6px 5px
        margin-top: 5px
        overflow: hidden
      .follow-common
        float left
        position relative
        line-height 24px
        background-color #7ab8f3
        margin 0 0 10px 10px
        padding 0 10px
        color #fff
        border-radius 4px
      .follow-agent
        color #fff
        margin 0 0 8px 8px
        font-size 12px
        &:hover
          .el-icon-close
            display block
        .el-icon-close
          display none
          position absolute
          right -10px
          top -10px
          width 24px
          height 24px
          font-size 12px
          line-height 24px
          transform scale(0.6)
          text-align center
          color #fff
          background-color #0f99fc
          border-radius 50%
          border 1px solid #cce6ff
          cursor pointer
      .follow-agent-wrap-btn
        display block !important
        line-height 0px
        float right
        cursor pointer
        color $c-main
      .line
        width: 30px;
        height: 1px;
        background-color: #dcdfe6;
        display: inline-block;
        margin: 0 13px;
    .submit
      text-align right
      margin-top 10px
      margin-bottom 28px
    .quality-check-realust-table
      /*height calc(100vh - 90px)*/
      /*padding 20px 20px 0*/
      /*overflow scroll*/
      .btn-wrap
        text-align right
        /*margin-bottom 20px*/
      .search-pagination
        margin: 10px 0px 0px 20px
        float right
      .deploy-btn
        margin-top 10px
      .deploy
        text-align right
        height 48px
        border-bottom none
        padding-left 14px

</style>
<style lang="stylus">
  .quality-check-resultAll
    .el-date-editor .el-range__icon
      margin-left -11px
    .el-date-editor .el-range-input
      width 40%
    .el-select-dropdown .el-popper .is-multiple
      min-width: 300px
      width: 300px
    .task-form-inline .el-select-dropdown .el-popper .is-multiple
      width: 300px
    .form-inline .el-select__tags-text 
      display inline-block
      max-width 140px
      overflow hidden
      text-overflow ellipsis
      white-space nowrap
    .el-tag__close.el-icon-close 
      top -3px
</style>
